package com.learn.service;

import com.learn.config.RpcDeCoder;
import com.learn.handler.UserServiceHandler;
import com.learn.pojo.RpcRequest;
import com.learn.utils.JSONSerializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Service;

/**
 * @program: rmi
 * @description
 * @author: luffy
 * @create: 2020-08-17 13:37
 */
@Service("IUserService")
public class UserServiceImpl implements IUserService {
    /**
     * 将来客户端要调用的远程方法
     *
     * @param msg
     * @return
     */
    public String sayHello(String msg) {
        System.out.println("你好吗？" + msg);
        return "你好吗？" + msg;
    }

    /**
     * 创建一个方法启动服务器
     * @param ip
     * @param port
     */
    public  void startServer(String ip,int port) throws InterruptedException {
        //1.创建练歌线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        //2.创建服务端启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();


        //3.配置启动引导对象
        serverBootstrap.group(bossGroup, workGroup)
                //设置通道为NIO
                .channel((NioServerSocketChannel.class))
                //创建监听channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();

                        //给管道对象设置编码
                        pipeline.addFirst(new RpcDeCoder(RpcRequest.class,new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new StringEncoder());

                        //把我们自己的ChannelHandler添加到通道中
                        pipeline.addLast(new UserServiceHandler());
                    }
                });

        //4.绑定端口
        serverBootstrap.bind(8999).sync();

    }
}
